package com.cherry.sdk.http.converter

import com.google.gson.TypeAdapter
import com.google.gson.stream.JsonReader
import com.google.gson.stream.JsonToken
import com.google.gson.stream.JsonWriter

import java.io.IOException

/**
 * 按值解析为枚举类型
 * @author 董棉生(dongmiansheng@parkingwang.com)
 * @since 18-11-16
 */
class ValueEnumAdapter<T : Enum<T>>(enumType: Class<T>) : TypeAdapter<T>() {

    private val mConstants: Array<T> = enumType.enumConstants

    @Throws(IOException::class)
    override fun write(out: JsonWriter, t: T?) {
        if (t == null) {
            out.value("")
        } else {
            out.value((t as ValueEnum).value.toString())
        }
    }

    @Throws(IOException::class)
    override fun read(reader: JsonReader): T? {
        val peek = reader.peek()
        val value = when (peek) {
            JsonToken.NUMBER -> reader.nextInt()
            JsonToken.STRING -> {
                val string = reader.nextString()
                if (string.isEmpty()) {
                    return null
                }
                Integer.parseInt(string)
            }
            JsonToken.NULL -> return null
            else -> throw IllegalStateException("Expected NUMBER but was " + peek + " " + reader.path)
        }
        for (constant in mConstants) {
            if ((constant as ValueEnum).value == value) {
                return constant
            }
        }
        return null
    }
}
